<template>
  <div class="app-container" ref="scrollContainer" style="overflow-y: auto;">
    <table>
      <thead>
        <tr>
          <th>序号</th>
          <th>物料名称</th>
          <th>物料编码</th>
          <th>物料规格</th>
          <th>物料单位</th>
          <th>基出用量</th>
          <th>操作</th>
        </tr>
        <BomTree :bomData="bomData" @toggle="toggle" @edit="edit" @remove="remove" />
      </thead>
    </table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';  // 引入 useRoute 和 useRouter
import axios from 'axios';
import BomTree from './BomTree.vue';

const bomData = ref([]);
const route = useRoute();

onMounted(() => {
  const bomcode = route.query.bomcode;
  if (bomcode) {
    fetchBomData(bomcode);
  } else {
    console.error('未获取到有效的 bomcode');
  }
});

const fetchBomData = async (bomcode) => {
  try {
    const response = await axios.get(`/api/Mbd_BOMxq/GetBomTree?bomcode=${bomcode}`);
    bomData.value = initOpenStatus(response.data);
    console.log(bomData.value);
  } catch (error) {
    console.error("获取BOM数据失败:", error);
  }
};

const initOpenStatus = (data) => {
  return data.map(item => {
    item.isOpen = false;
    if (item.children) {
      item.children = initOpenStatus(item.children);
    }
    return item;
  });
};

const toggle = (item) => {
  if (item) {
    const scrollContainer = document.querySelector('.app-container');
    if (scrollContainer) {
      const scrollTop = scrollContainer.scrollTop;
      item.isOpen =!item.isOpen;
      setTimeout(() => {
        scrollContainer.scrollTop = scrollTop;
      }, 0);
    }
  }
};

const edit = (item) => {
  console.log("编辑:", item);
};

const remove = (item) => {
  console.log("删除:", item);
};
</script>

<style scoped>
.app-container {
  max-height: 80vh; /* 根据需要调整容器高度 */
}
table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center; /* 添加这一行，使字体居中 */
}
</style>